package com.gzw.jackyweather;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gzw.jackyweather.db.CityManger;
import com.gzw.jackyweather.db.Skin;
import com.zhy.autolayout.utils.AutoUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

public class SkinActivity extends BaseActivity {

    private Button btn_back;
    private GridView gv;
    private List<Skin> skins;
    private final int IMAGE_CODE = 0;
    Uri bitmapUri = null;
    private final String IMAGE_TYPE = "image/*";

    private ImageView iv_backGroud;

    private GridViewAdapter adapter;

    @Override
    public int getContentViewID() {
        return R.layout.activity_skin;
    }

    @Override
    protected void initView() {

        skins = new ArrayList<>();
        btn_back = (Button) findViewById(R.id.btn_back);
        gv = (GridView) findViewById(R.id.gv);
        iv_backGroud = (ImageView) findViewById(R.id.iv_background);
        skins.addAll(DataSupport.findAll(Skin.class));

        if (skins.size() != 0) {
            skins.add(new Skin());
            adapter = new GridViewAdapter(skins);
            gv.setAdapter(adapter);
        }

        List<Skin> skin = DataSupport.where("isDefault = ?", "1").find(Skin.class);
        if (skin.size() != 0) {
            if (skin.get(0).getImgId() == 0) {
                Glide.with(SkinActivity.this).load(skin.get(0).getFlag()).into(iv_backGroud);
            } else {
                iv_backGroud.setImageResource(skin.get(0).getImgId());
            }

        }

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    class GridViewAdapter extends BaseAdapter {

        private List<Skin> list;

        public GridViewAdapter(List<Skin> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.skin_item, parent, false);
                holder.iv_background = (ImageView) convertView.findViewById(R.id.iv_bg);
                holder.ll = (RelativeLayout) convertView.findViewById(R.id.ll);
                holder.ll1 = (LinearLayout) convertView.findViewById(R.id.ll1);
                holder.tv_moren = (TextView) convertView.findViewById(R.id.tv_moren);
                holder.btn_add = (Button) convertView.findViewById(R.id.btn_add);
                convertView.setTag(holder);
                AutoUtils.auto(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (list.get(position).getImgId() == 0) {
                Glide.with(MyApplication.getContext()).load(list.get(position).getFlag()).into(holder.iv_background);
            } else {
                holder.iv_background.setImageResource(list.get(position).getImgId());
            }

            if (position == list.size() - 1) {
                holder.ll.setVisibility(View.GONE);
                holder.ll1.setVisibility(View.VISIBLE);
            } else {
                holder.ll.setVisibility(View.VISIBLE);
                holder.ll1.setVisibility(View.GONE);
            }

            holder.tv_moren.setText(list.get(position).isDefault() ? "默认" : "设置默认");
            holder.tv_moren.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setDefault(false);
                        ContentValues values = new ContentValues();
                        values.put("isDefault", 0);
                        DataSupport.updateAll(Skin.class, values, "imgId = ?", list.get(i).getImgId() + "");
                    }
                    ContentValues values1 = new ContentValues();
                    values1.put("isDefault", 1);
                    DataSupport.updateAll(Skin.class, values1, "imgId = ?", list.get(position).getImgId() + "");

                    list.get(position).setDefault(true);
                    if (list.get(position).getImgId() == 0) {
                        Glide.with(SkinActivity.this).load(list.get(position).getFlag()).into(iv_backGroud);
                    } else {
                        iv_backGroud.setImageResource(list.get(position).getImgId());
                    }
                    notifyDataSetChanged();
                }
            });

            holder.btn_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //获取权限
                    if (ContextCompat.checkSelfPermission(SkinActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(SkinActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    } else {
                        //更换被背景,打开相册
                        selectImage();
                    }

                }
            });
            return convertView;
        }


        //添加一个图片
        public void addImage(Uri uri) {

            Skin skin = new Skin();
            skin.setDefault(false);
            skin.setFlag(uri.toString());
            skin.setImgId(0);
            skin.save();
            list.add(list.size() - 1, skin);
            notifyDataSetChanged();
        }
    }

    class ViewHolder {
        ImageView iv_background;
        LinearLayout ll1;
        RelativeLayout ll;
        TextView tv_moren;
        Button btn_add;
    }

    private void selectImage() {

        //获取相册的图片
        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        getAlbum.setType(IMAGE_TYPE);
        startActivityForResult(getAlbum, IMAGE_CODE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_CODE:
                    Uri originalUri = data.getData();  //获得图片的uri
                    bitmapUri = originalUri;
                    //使用Glide加载图片
                    adapter.addImage(bitmapUri);

                    break;
            }
        }
    }

    //申请权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    selectImage();
                } else {
                    Toast.makeText(this, "你需要打开权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
